"""
患者管理 API
严格按照原 Flask 项目的接口实现，保持 100% 兼容性
"""
import os
from typing import Optional, List
from fastapi import APIRouter, Depends, Query, Request, UploadFile, File
from fastapi.responses import FileResponse
# pyright: reportMissingImports=false
from sqlalchemy.ext.asyncio import AsyncSession

from  core.database import get_db
from  api.deps import get_current_active_doctor
from  models.doctor import Doctor
from  schemas.patient import PatientCreate, PatientUpdate, PatientResponse
from  crud import patient as crud_patient

router = APIRouter()

# 头像上传目录配置
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'uploads', 'avatars')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 允许的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

def allowed_file(filename: str) -> bool:
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@router.post("")
async def create_patient(
    patient_in: PatientCreate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    创建患者
    原接口: POST /api/patients
    需要JWT认证
    """
    try:
        # 检查身份证号是否已存在
        if patient_in.id_card:
            existing_patient = await crud_patient.get_by_id_card(db, id_card=patient_in.id_card)
            if existing_patient and existing_patient.status == 1:
                return {
                    "message": "该身份证号已存在",
                    "code": 1
                }
        
        # 设置归属医生为当前登录医生
        patient_data = patient_in.model_dump()
        patient_data['doctor_id'] = current_doctor.id
        
        patient = await crud_patient.create(db, obj_in=PatientCreate(**patient_data))
        await db.commit()
        
        return {
            "message": "病人信息创建成功",
            "id": str(patient.id),
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"创建失败: {str(e)}",
            "code": 1
        }


@router.get("")
async def get_patients(
    page: int = Query(1, ge=1, description="页码"),
    per_page: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="患者姓名（模糊查询）"),
    id_card: Optional[str] = Query(None, description="身份证号（模糊查询）"),
    phone: Optional[str] = Query(None, description="手机号（模糊查询）"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取患者列表（分页+模糊搜索）
    原接口: GET /api/patients
    需要JWT认证
    
    ⚠️ 完全按照原 Flask 项目逻辑实现
    """
    try:
        # 计算 skip
        skip = (page - 1) * per_page
        
        # 处理空字符串参数（前端可能发送空字符串）
        name = name if name and name.strip() else None
        id_card = id_card if id_card and id_card.strip() else None
        phone = phone if phone and phone.strip() else None
        
        # 计算总数（使用 CRUD 的 count 方法）
        total = await crud_patient.count_by_doctor(
            db,
            doctor_id=current_doctor.id,
            name=name,
            id_card=id_card,
            phone=phone
        )
        
        # 计算总页数
        total_pages = (total + per_page - 1) // per_page if total > 0 else 0
        
        # 获取患者列表（使用 get_by_doctor，支持条件查询）
        from sqlalchemy import select, and_
        from  models.patient import Patient
        
        query = select(Patient).where(
            Patient.doctor_id == current_doctor.id
        ).where(Patient.status == 1)
        
        # 添加模糊查询条件（与原 Flask 项目一致）
        if name:
            query = query.where(Patient.name.ilike(f"%{name}%"))
        if id_card:
            query = query.where(
                and_(
                    Patient.id_card.isnot(None),
                    Patient.id_card.ilike(f"%{id_card}%")
                )
            )
        if phone:
            query = query.where(
                and_(
                    Patient.phone.isnot(None),
                    Patient.phone.ilike(f"%{phone}%")
                )
            )
        
        # 排序、分页
        query = query.order_by(Patient.updated_at.desc()).offset(skip).limit(per_page)
        result = await db.execute(query)
        patients = list(result.scalars().all())
        
        # 使用 Schema 转换为 Flask 格式
        patients_data = [
            PatientResponse.model_validate(p).to_flask_format()
            for p in patients
        ]
        
        return {
            "message": "获取病人列表成功",
            "data": {
                "patients": patients_data,
                "total": total,
                "total_pages": total_pages,
                "current_page": page,
                "per_page": per_page
            },
            "code": 0
        }
        
    except Exception as e:
        import traceback
        traceback.print_exc()  # 打印详细错误信息
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1,
            "data": {"error_detail": str(e)}
        }


@router.get("/all")
async def get_all_patients(
    name: Optional[str] = Query(None, description="患者姓名（模糊查询）"),
    id_card: Optional[str] = Query(None, description="身份证号（模糊查询）"),
    phone: Optional[str] = Query(None, description="手机号（模糊查询）"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取所有患者列表（不分页）
    原接口: GET /api/patients/all
    需要JWT认证
    """
    try:
        # 如果有搜索条件
        if name or id_card or phone:
            keyword = name or id_card or phone
            patients = await crud_patient.search(
                db,
                keyword=keyword,
                doctor_id=current_doctor.id,
                skip=0,
                limit=10000  # 大数字表示不分页
            )
        else:
            patients = await crud_patient.get_by_doctor(
                db,
                doctor_id=current_doctor.id,
                skip=0,
                limit=10000
            )
        
        # 使用 Schema 转换为 Flask 格式
        patients_data = [
            PatientResponse.model_validate(p).to_flask_format()
            for p in patients
        ]
        
        return {
            "message": "获取患者列表成功",
            "data": patients_data,
            "total": len(patients_data),
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.get("/{patient_id}")
async def get_patient(
    patient_id: str,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取患者详情
    原接口: GET /api/patients/<patient_id>
    需要JWT认证
    """
    try:
        # 转换 ID
        try:
            patient_id_int = int(patient_id)
        except:
            return {
                "message": "无效的患者ID",
                "code": 1
            }
        
        # 获取患者
        patient = await crud_patient.get(db, id=patient_id_int)
        
        if not patient or patient.status != 1:
            return {
                "message": "病人不存在或您无权访问",
                "code": 1
            }
        
        # 权限检查：只能查看自己的患者
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "病人不存在或您无权访问",
                "code": 1
            }
        
        # 使用 Schema 转换为 Flask 格式
        patient_data = PatientResponse.model_validate(patient).to_flask_format()
        
        return {
            "message": "获取病人信息成功",
            "data": patient_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.put("/{patient_id}")
async def update_patient(
    patient_id: str,
    patient_update: PatientUpdate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    更新患者信息
    原接口: PUT /api/patients/<patient_id>
    需要JWT认证
    
    ⚠️ 注意：不能修改 _id 和 doctor_id（归属医生）字段
    """
    try:
        # 转换 ID
        try:
            patient_id_int = int(patient_id)
        except:
            return {
                "message": "无效的患者ID",
                "code": 1
            }
        
        # 获取患者
        patient = await crud_patient.get(db, id=patient_id_int)
        
        if not patient or patient.status != 1:
            return {
                "message": "病人不存在或您无权修改",
                "code": 1
            }
        
        # 权限检查
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "病人不存在或您无权修改",
                "code": 1
            }
        
        # 检查身份证号是否与其他患者重复
        if patient_update.id_card and patient_update.id_card != patient.id_card:
            existing = await crud_patient.get_by_id_card(db, id_card=patient_update.id_card)
            if existing and existing.id != patient_id_int and existing.status == 1:
                return {
                    "message": "该身份证号已被其他患者使用",
                    "code": 1
                }
        
        # ⚠️ 关键修改：确保不能修改 doctor_id 字段（与原 Flask 项目保持一致）
        from datetime import datetime, timezone
        update_data = patient_update.model_dump(exclude_unset=True)
        
        # 强制删除 doctor_id，防止修改归属医生
        if 'doctor_id' in update_data:
            del update_data['doctor_id']
        
        update_data["updated_at"] = datetime.now(timezone.utc)
        
        for key, value in update_data.items():
            setattr(patient, key, value)
        
        db.add(patient)
        await db.commit()
        
        return {
            "message": "病人信息更新成功",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"更新失败: {str(e)}",
            "code": 1
        }


@router.delete("/{patient_id}")
async def delete_patient(
    patient_id: str,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    删除患者（软删除）
    原接口: DELETE /api/patients/<patient_id>
    需要JWT认证
    """
    try:
        # 转换 ID
        try:
            patient_id_int = int(patient_id)
        except:
            return {
                "message": "无效的患者ID",
                "code": 1
            }
        
        # 获取患者
        patient = await crud_patient.get(db, id=patient_id_int)
        
        if not patient or patient.status != 1:
            return {
                "message": "病人不存在或您无权删除",
                "code": 1
            }
        
        # 权限检查
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "病人不存在或您无权删除",
                "code": 1
            }
        
        # 软删除
        from datetime import datetime, timezone
        patient.status = 0
        patient.updated_at = datetime.now(timezone.utc)
        db.add(patient)
        await db.commit()
        
        return {
            "message": "病人信息删除成功",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"删除失败: {str(e)}",
            "code": 1
        }


@router.delete("/batch")
async def batch_delete_patients(
    request: Request,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    批量删除患者
    原接口: DELETE /api/patients/batch
    需要JWT认证
    """
    try:
        data = await request.json()
        
        if not data or 'patient_ids' not in data:
            return {
                "message": "缺少必要参数: patient_ids",
                "code": 1
            }
        
        patient_ids = data['patient_ids']
        if not isinstance(patient_ids, list) or not patient_ids:
            return {
                "message": "patient_ids必须是非空数组",
                "code": 1
            }
        
        # 转换 ID
        try:
            patient_ids_int = [int(pid) for pid in patient_ids]
        except:
            return {
                "message": "无效的患者ID格式",
                "code": 1
            }
        
        # 批量软删除
        from datetime import datetime, timezone
        from sqlalchemy import update
        from  models.patient import Patient
        
        result = await db.execute(
            update(Patient)
            .where(Patient.id.in_(patient_ids_int))
            .where(Patient.doctor_id == current_doctor.id)
            .where(Patient.status == 1)
            .values(status=0, updated_at=datetime.now(timezone.utc))
        )
        
        await db.commit()
        
        modified_count = result.rowcount
        
        if modified_count == 0:
            return {
                "message": "未找到可删除的患者",
                "code": 1
            }
        
        return {
            "message": f"成功删除{modified_count}个患者",
            "deleted_count": modified_count,
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"批量删除失败: {str(e)}",
            "code": 1
        }


@router.get("/wx-patient/{patient_id}")
async def wx_get_patient(
    patient_id: str,
    db: AsyncSession = Depends(get_db)
):
    """
    患者端获取患者信息（无需JWT认证）
    原接口: GET /api/patients/wx-patient/<patient_id>
    ⚠️ 此接口供微信小程序患者端使用，不需要 JWT 认证
    """
    try:
        # 转换 ID
        try:
            patient_id_int = int(patient_id)
        except:
            return {
                "message": "无效的患者ID",
                "code": 1
            }
        
        # 获取患者
        patient = await crud_patient.get(db, id=patient_id_int)
        
        if not patient or patient.status != 1:
            return {
                "message": "病人不存在",
                "code": 1
            }
        
        # 使用 Schema 转换为 Flask 格式
        patient_data = PatientResponse.model_validate(patient).to_flask_format()
        
        return {
            "message": "获取病人信息成功",
            "data": patient_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.post("/export")
async def export_patients(
    request: Request,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    导出指定患者信息（Excel）
    原接口: POST /api/patients/export
    需要JWT认证
    """
    try:
        from fastapi.responses import StreamingResponse
        import openpyxl
        from openpyxl.styles import Font, Alignment, PatternFill
        from io import BytesIO
        import urllib.parse
        from datetime import datetime
        
        data = await request.json()
        
        # 验证请求参数
        if not data or 'patient_ids' not in data:
            return {
                "message": "缺少必要参数: patient_ids",
                "code": 1
            }
        
        patient_ids = data['patient_ids']
        if not isinstance(patient_ids, list) or not patient_ids:
            return {
                "message": "patient_ids必须是非空数组",
                "code": 1
            }
        
        # 转换 ID
        try:
            patient_ids_int = [int(pid) for pid in patient_ids]
        except:
            return {
                "message": "无效的患者ID格式",
                "code": 1
            }
        
        # 查询指定的患者信息
        from sqlalchemy import select
        from  models.patient import Patient
        
        result = await db.execute(
            select(Patient)
            .where(Patient.id.in_(patient_ids_int))
            .where(Patient.doctor_id == current_doctor.id)
            .where(Patient.status == 1)
            .order_by(Patient.created_at.asc())
        )
        patients = list(result.scalars().all())
        
        if not patients:
            return {
                "message": "未找到可导出的患者信息",
                "code": 1
            }
        
        # 创建 Excel 文件
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "患者信息"
        
        # 设置表头
        headers = [
            '序号', '姓名', '性别', '年龄', '手机号', '身份证号', '身高(cm)', '体重(kg)',
            '惯用手', '糖尿病', '高血压', '高血脂', '卒中史', '吸烟史', '吸烟量(支/天)',
            '吸烟年数', '已戒烟', '饮酒史', '饮酒量(ml/天)', '饮酒年数', '已戒酒',
            '心脏病', '房颤', '睡眠呼吸暂停', '创建时间', '更新时间'
        ]
        
        # 写入表头
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = Font(bold=True, color="FFFFFF")
            cell.fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
            cell.alignment = Alignment(horizontal="center", vertical="center")
        
        # 写入数据
        for row_idx, patient in enumerate(patients, 2):
            data_row = [
                row_idx - 1,  # 序号
                patient.name,
                patient.gender if patient.gender else '',
                patient.age if patient.age else '',
                patient.phone if patient.phone else '',
                patient.id_card if patient.id_card else '',
                float(patient.height) if patient.height else '',
                float(patient.weight) if patient.weight else '',
                patient.handedness if patient.handedness else '',
                '是' if patient.diabetes else '否',
                '是' if patient.hypertension else '否',
                '是' if patient.hyperlipidemia else '否',
                '是' if patient.stroke_history else '否',
                '是' if patient.has_smoking_history else '否',
                patient.smoking_amount if patient.smoking_amount else '',
                patient.smoking_years if patient.smoking_years else '',
                '是' if patient.has_quit_smoking else '否',
                '是' if patient.has_drinking_history else '否',
                patient.drinking_amount if patient.drinking_amount else '',
                patient.drinking_years if patient.drinking_years else '',
                '是' if patient.has_quit_drinking else '否',
                '是' if patient.heart_disease else '否',
                '是' if patient.atrial_fibrillation else '否',
                '是' if patient.sleep_apnea else '否',
                patient.created_at.strftime('%Y-%m-%d %H:%M:%S') if patient.created_at else '',
                patient.updated_at.strftime('%Y-%m-%d %H:%M:%S') if patient.updated_at else ''
            ]
            
            for col, value in enumerate(data_row, 1):
                cell = ws.cell(row=row_idx, column=col, value=value)
                cell.alignment = Alignment(horizontal="center", vertical="center")
        
        # 调整列宽
        for column in ws.columns:
            max_length = 0
            column_letter = column[0].column_letter
            for cell in column:
                try:
                    if len(str(cell.value)) > max_length:
                        max_length = len(str(cell.value))
                except:
                    pass
            adjusted_width = min(max_length + 2, 20)
            ws.column_dimensions[column_letter].width = adjusted_width
        
        # 保存到内存
        output = BytesIO()
        wb.save(output)
        output.seek(0)
        
        # 生成文件名
        filename_utf8 = f"患者信息导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        encoded_filename = urllib.parse.quote(filename_utf8)
        
        # 返回文件流
        return StreamingResponse(
            output,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={
                "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
            }
        )
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return {
            "message": f"导出失败: {str(e)}",
            "code": 1
        }


@router.get("/export/all")
async def export_all_patients(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    导出当前医生的所有患者信息（Excel）
    原接口: GET /api/patients/export/all
    需要JWT认证
    """
    try:
        from fastapi.responses import StreamingResponse
        import openpyxl
        from openpyxl.styles import Font, Alignment, PatternFill
        from io import BytesIO
        import urllib.parse
        from datetime import datetime
        
        # 查询当前医生的所有患者
        from sqlalchemy import select
        from  models.patient import Patient
        
        result = await db.execute(
            select(Patient)
            .where(Patient.doctor_id == current_doctor.id)
            .where(Patient.status == 1)
            .order_by(Patient.created_at.asc())
        )
        patients = list(result.scalars().all())
        
        if not patients:
            return {
                "message": "没有患者信息可导出",
                "code": 1
            }
        
        # 创建 Excel 文件（与 export_patients 相同的逻辑）
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "患者信息"
        
        # 设置表头
        headers = [
            '序号', '姓名', '性别', '年龄', '手机号', '身份证号', '身高(cm)', '体重(kg)',
            '惯用手', '糖尿病', '高血压', '高血脂', '卒中史', '吸烟史', '吸烟量(支/天)',
            '吸烟年数', '已戒烟', '饮酒史', '饮酒量(ml/天)', '饮酒年数', '已戒酒',
            '心脏病', '房颤', '睡眠呼吸暂停', '创建时间', '更新时间'
        ]
        
        # 写入表头
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = Font(bold=True, color="FFFFFF")
            cell.fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
            cell.alignment = Alignment(horizontal="center", vertical="center")
        
        # 写入数据
        for row_idx, patient in enumerate(patients, 2):
            data_row = [
                row_idx - 1,
                patient.name,
                patient.gender if patient.gender else '',
                patient.age if patient.age else '',
                patient.phone if patient.phone else '',
                patient.id_card if patient.id_card else '',
                float(patient.height) if patient.height else '',
                float(patient.weight) if patient.weight else '',
                patient.handedness if patient.handedness else '',
                '是' if patient.diabetes else '否',
                '是' if patient.hypertension else '否',
                '是' if patient.hyperlipidemia else '否',
                '是' if patient.stroke_history else '否',
                '是' if patient.has_smoking_history else '否',
                patient.smoking_amount if patient.smoking_amount else '',
                patient.smoking_years if patient.smoking_years else '',
                '是' if patient.has_quit_smoking else '否',
                '是' if patient.has_drinking_history else '否',
                patient.drinking_amount if patient.drinking_amount else '',
                patient.drinking_years if patient.drinking_years else '',
                '是' if patient.has_quit_drinking else '否',
                '是' if patient.heart_disease else '否',
                '是' if patient.atrial_fibrillation else '否',
                '是' if patient.sleep_apnea else '否',
                patient.created_at.strftime('%Y-%m-%d %H:%M:%S') if patient.created_at else '',
                patient.updated_at.strftime('%Y-%m-%d %H:%M:%S') if patient.updated_at else ''
            ]
            
            for col, value in enumerate(data_row, 1):
                cell = ws.cell(row=row_idx, column=col, value=value)
                cell.alignment = Alignment(horizontal="center", vertical="center")
        
        # 调整列宽
        for column in ws.columns:
            max_length = 0
            column_letter = column[0].column_letter
            for cell in column:
                try:
                    if len(str(cell.value)) > max_length:
                        max_length = len(str(cell.value))
                except:
                    pass
            adjusted_width = min(max_length + 2, 20)
            ws.column_dimensions[column_letter].width = adjusted_width
        
        # 保存到内存
        output = BytesIO()
        wb.save(output)
        output.seek(0)
        
        # 生成文件名
        filename_utf8 = f"全部患者信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        encoded_filename = urllib.parse.quote(filename_utf8)
        
        # 返回文件流
        return StreamingResponse(
            output,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={
                "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
            }
        )
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return {
            "message": f"导出失败: {str(e)}",
            "code": 1
        }


@router.post("/{patient_id}/avatar")
async def upload_avatar(
    patient_id: str,
    avatar: UploadFile = File(...),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    上传患者头像
    原接口: POST /api/patients/<patient_id>/avatar
    需要JWT认证
    """
    try:
        # 转换 ID
        try:
            patient_id_int = int(patient_id)
        except:
            return {
                "message": "无效的患者ID",
                "code": 1
            }
        
        # 检查患者是否存在且属于当前医生
        patient = await crud_patient.get(db, id=patient_id_int)
        
        if not patient or patient.status != 1:
            return {
                "message": "患者不存在或您无权操作",
                "code": 1
            }
        
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "患者不存在或您无权操作",
                "code": 1
            }
        
        # 检查文件名
        if not avatar.filename:
            return {
                "message": "未选择文件",
                "code": 1
            }
        
        # 检查文件类型
        if not allowed_file(avatar.filename):
            return {
                "message": "不支持的文件类型",
                "code": 1
            }
        
        # 获取文件扩展名
        ext = avatar.filename.rsplit('.', 1)[1].lower()
        filename = f"{patient_id}.{ext}"
        filepath = os.path.join(UPLOAD_FOLDER, filename)
        
        # 删除旧头像（如果存在）
        for old_ext in ALLOWED_EXTENSIONS:
            old_file = os.path.join(UPLOAD_FOLDER, f"{patient_id}.{old_ext}")
            if os.path.exists(old_file):
                os.remove(old_file)
        
        # 保存新文件
        with open(filepath, "wb") as f:
            content = await avatar.read()
            f.write(content)
        
        # 更新患者记录中的头像字段
        from datetime import datetime, timezone
        avatar_url = f'/api/patients/patients/{patient_id}/avatar/view'
        patient.avatar = avatar_url
        patient.updated_at = datetime.now(timezone.utc)
        db.add(patient)
        await db.commit()
        
        return {
            "message": "头像上传成功",
            "data": {"avatar_url": avatar_url},
            "code": 0
        }
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return {
            "message": f"上传失败: {str(e)}",
            "code": 1
        }


@router.get("/{patient_id}/avatar/view")
async def view_avatar(patient_id: str):
    """
    获取患者头像
    原接口: GET /api/<patient_id>/avatar/view
    ⚠️ 此接口无需JWT认证（公开访问）
    """
    try:
        # 查找患者的头像文件
        for ext in ALLOWED_EXTENSIONS:
            filename = f"{patient_id}.{ext}"
            filepath = os.path.join(UPLOAD_FOLDER, filename)
            if os.path.exists(filepath):
                return FileResponse(filepath)
        
        # 如果没有找到头像，返回404
        return {
            "message": "头像不存在",
            "code": 1
        }
        
    except Exception as e:
        return {
            "message": f"获取头像失败: {str(e)}",
            "code": 1
        }


